import {defineStore} from 'pinia';
import {openDB} from 'idb';

const DB_NAME = 'NodeLibraryDB';
const STORE_NAME = 'templates';
const DB_VERSION = 1;

export const useNodeLibraryStore = defineStore('nodeLibrary', {
  state: () => ({
    templates: [],
  }),

  actions: {
    async getDB() {
      return await openDB(DB_NAME, DB_VERSION, {
        upgrade(db) {
          if (!db.objectStoreNames.contains(STORE_NAME)) {
            db.createObjectStore(STORE_NAME, {keyPath: 'id'});
          }
        },
      });
    },

    async fetchTemplates() {
      try {
        const db = await this.getDB();
        const templates = await db.getAll(STORE_NAME);
        this.templates = templates.map(t => t.data || t);
        return this.templates;
      } catch (error) {
        console.error('Error fetching templates:', error);
        return [];
      }
    },

    async addTemplate(template) {
      try {
        const db = await this.getDB();
        // 确保数据可以被序列化
        const templateData = {
          id: template.id,
          data: JSON.parse(JSON.stringify({
            id: template.id,
            name: template.name,
            type: template.type,
            content: template.content,
            input: template.input,
            output: template.output,
            description: template.description || ''
          }))
        };
        
        await db.put(STORE_NAME, templateData);
        await this.fetchTemplates();
        return true;
      } catch (error) {
        console.error('Error adding template:', error);
        return false;
      }
    },

    async deleteTemplate(id) {
      try {
        const db = await this.getDB();
        await db.delete(STORE_NAME, id);
        await this.fetchTemplates();
        return true;
      } catch (error) {
        console.error('Error deleting template:', error);
        return false;
      }
    },
  },
});
